package com.vision.web.aop;

import com.vision.common.aes.AES;
import com.vision.web.annotation.Decode;
import com.vision.web.annotation.Encode;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

;

/**
 * Created by jiaobuchong on 12/23/15.
 */
@Aspect
@Component
public class ParamsAspect {
    private static final Logger logger = LoggerFactory.getLogger(ParamsAspect.class);

    // 定义切点Pointcut
    @Pointcut("execution(* com.vision.web.controller..*(..))")
    public void excudeService() {
    }

    // @Before("excudeService()")
    // public void doAround(JoinPoint pjp) throws Throwable {
    //     RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    //     ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    //     HttpServletRequest request = sra.getRequest();
    //     String url = request.getRequestURL().toString();
    //     String method = request.getMethod();
    //     String uri = request.getRequestURI();
    //     String queryString = request.getQueryString();
    //     logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
    //     String params = request.getParameter("params");
    //     if (params != null) {
    //         AES.decode(params);
    //     }
    //
    //     // result的值就是被拦截方法的返回值
    //     // Object result = pjp.proceed();
    //     // Gson gson = new Gson();
    //     // logger.info("请求结束，controller的返回值是 " + gson.toJson(result));
    //     // pjp.
    // }


    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Object[] params = pjp.getArgs();
        Method method = signature.getMethod();
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < params.length; i++) {
            Object tmpObject = params[i];
            if (annotations.length > 0) {
                for (Annotation annotation : annotations[i]) {
                    if (annotation.annotationType() == Decode.class) {
                        params[i] = AES.decode((String) tmpObject);
                    }
                }
            }
        }
        Object result = pjp.proceed(params);
        Encode annotation = method.getAnnotation(Encode.class);
        if (annotation != null) {
            result = AES.encode((String) result);
        }
        return result;
    }


}